package com.sfpay.coreplatform.order.service.composite.common;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sfpay.coreplatform.order.common.OrderResponseCode;
import com.sfpay.coreplatform.order.service.composite.IHandler;
import com.sfpay.coreplatform.order.service.exception.OrderServiceException;
import com.sfpay.coreplatform.order.valueobject.dto.PayRequest;
import com.sfpay.coreplatform.order.valueobject.dto.Response;

public class PayChannelHandlerFactory {

	private final static Logger logger = LoggerFactory
			.getLogger(PayChannelHandlerFactory.class);
	private List<IHandler> handlers = new ArrayList<IHandler>();

	/**
	 * 增加业务处理组件
	 * 
	 * @param handler
	 */
	public void addHandler(IHandler handler) {

		handlers.add(handler);
	}

	/**
	 * 开始执行处理业务链
	 * 
	 * @param request
	 * @param payContext
	 * @return
	 */
	public Response startHandler(PayRequest request, PayContext payContext) {
		Response response = null;
		for (IHandler handler : handlers) {
			logger.debug("---"+request.getOutTradeNo()+"--------------- "+handler.getHandlerName()+" Begin--------------");
			try {
				response = handler.Handler(request, payContext);
				if(response==null){
					response = new Response();
					response.setReturnCode(OrderResponseCode.ORDER_OTHER_EXCEPTION);
					response.setReturnMsg(handler.getHandlerName()+" handeler fail");					 
					break;
				}
				if (response.getReturnCode() < 0) {// 处理失败结束
					break;
				}
				if(response.getReturnCode()>10000){//业务处理已经成功进行结束
					break;
				}
				 
			} catch (OrderServiceException e) {

				response = new Response();

				response.setReturnCode(e.getCode());
				response.setReturnMsg(e.getMessage());
				break;
			} catch (Exception e) {
				response = new Response();
				response.setReturnCode(OrderResponseCode.ORDER_OTHER_EXCEPTION);
				response.setReturnMsg(handler.getHandlerName()+" handeler fail ;"+e.getMessage());
				break;
			}

			logger.debug("---"+request.getOutTradeNo()+"--------------- "+handler.getHandlerName()+" end--------------");
		}

		return response;
	}

}
